#!/bin/bash
#
# unmount luks-encrypted files and partitions...
#

luks_umount() {
	# something like this:
	#  /dev/mapper/luksfile11171 on /mnt/+mnt+sda3+slackosave_luks.4fs type ext4 (rw,relatime,data=ordered)
	read -r device on mountpoint etc <<< "$@"
	[ "$MOUNTPOINT" ] && mountpoint="$MOUNTPOINT" # /mnt/+mnt+sda3+slackosave_luks.4fs
	mpbase=$(basename "$mountpoint")  # +mnt+sda3+slackosave_luks.4fs
	mpbase=${mpbase##*\+}             # slackosave_luks.4fs
	#--
	LUKS_DEVICE=$(basename "$device") # luksfile132434, lukspartition2453
	#                                busybox    losetup-FULL
	DEVLOOP=$(losetup -a | grep -E "/${mpbase}$|/${mpbase})$" | cut -f 1 -d ':')
	#--
	umount "$mountpoint"
	cryptsetup luksClose -v ${LUKS_DEVICE}
	retval=$?
	if [ "$DEVLOOP" ] ; then
		losetup -vd ${DEVLOOP}
		retval=$?
	fi
	return $retval
}


#================================================================

if [ "${0##*/}" != "umount.crypto_LUKS" ] ; then
	#being sourced...
	return
fi

if [ "$1" = "all" ] ; then
	mount | grep -E '/dev/mapper/lukspartition|/dev/mapper/luksfile' | \
	while read i ; do
		luks_umount "$i"
	done
	for LUKS_DEVICE in $(ls /dev/mapper | grep -vE '^control$|savefile|savepartition')
	do
		cryptsetup luksClose -v ${LUKS_DEVICE}
	done
	exit
fi

#================================================================

if [ "$1" ] ; then

	MOUNTPOINT="$1"
	mntinfo=$(mount | grep " $MOUNTPOINT ")
	case "$mntinfo" in
	"/dev/mapper/luksfile"*|"/dev/mapper/lukspartition"*)
		luks_umount "$mntinfo"
		RETVAL=$?
		;;
	*) exit 1 ;;
	esac

	#===============================================================
	# rox - puppy

	if [ $RETVAL -eq 0 ] ; then
		if [ -f /usr/local/pup_event/frontend_funcs ] ; then
			#ROX: create or refresh desktop icon
			/usr/local/pup_event/frontend_funcs rox_umount_luks "$DEVNAME"
		fi
	fi

	#v409, instead just make sure the symlink stays there...
	if [ ! -L /etc/mtab ];then
	 rm -f /etc/mtab
	 ln -s /proc/mounts /etc/mtab
	fi

	##################################################################

	exit $RETVAL

fi

exit 1

### END ###
